package com.xiaoran.client.connector;

import com.xiaoran.client.channel.ChannelHolder;
import com.xiaoran.client.channel.ProviderService;
import com.xiaoran.client.run.RpcRequestManager;
import com.xiaoran.common.utils.SpringBeanFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.util.concurrent.CountDownLatch;

public class RpcClientConnector  implements Runnable{
    private static final Logger LOGGER = LoggerFactory.getLogger(RpcClientConnector.class);
    
    private String requestId;
    private ProviderService providerService;
    private CountDownLatch countDownLatch;
    private RpcClientInitializer rpcClientInitializer;

    public RpcClientConnector(String requestId, ProviderService providerService, CountDownLatch countDownLatch) {
        this.requestId = requestId;
        this.providerService = providerService;
        this.countDownLatch = countDownLatch;
        this.rpcClientInitializer = SpringBeanFactory.getBean(RpcClientInitializer.class);
    }

    @Override
    public void run() {
        EventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(worker)
                .channel(NioSocketChannel.class)
                .remoteAddress(providerService.getServerIp(),providerService.getNetworkPort())
                .handler(rpcClientInitializer);
        try {
            ChannelFuture future = bootstrap.connect().sync();
            if (future.isSuccess()) {
                ChannelHolder channelHolder = ChannelHolder.builder()
                        .channel(future.channel())
                        .eventLoopGroup(worker)
                        .build();
                //注册到RPC请求管理器
                RpcRequestManager.registerChannelHolder(requestId, channelHolder);
                LOGGER.info("Construct a connector with service provider[{}:{}] successfully", providerService.getServerIp(), providerService.getNetworkPort());
                countDownLatch.countDown();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
